package timbap.visualizer.coreplugins.lib.artworkhue;

import timbap.visualizer.api.context.playlist.PlaylistManager;
import timbap.visualizer.api.context.textures.TextureCacheManager;
import timbap.visualizer.api.model.PlaylistEntry;
import timbap.visualizer.api.model.ArtworkData;
import timbap.visualizer.api.plugin.poscloud.cache.PosCloudCacheEntry;
import timbap.visualizer.api.plugin.poscloud.cache.AbstractPosCloudMapXmlAdapter;

import java.awt.*;
import java.io.File;
import java.net.URI;

public class ArtworkHuePosCloudMapXmlAdapter extends AbstractPosCloudMapXmlAdapter<HueComparableColor> {

    private PlaylistManager playlistManager;
    private TextureCacheManager textureCacheManager;
    
    public ArtworkHuePosCloudMapXmlAdapter(PlaylistManager pPlaylistManager, TextureCacheManager pTextureCacheManager) {
        playlistManager = pPlaylistManager;
        textureCacheManager = pTextureCacheManager;
    }

    public HueComparableColor unmarshalPosCloudElement(PosCloudCacheEntry pCacheEntry) {
        return new HueComparableColor(
                Color.decode(pCacheEntry.getValue().toString()),
                             Long.parseLong(pCacheEntry.getChecksum()));
    }

    public PlaylistEntry unmarshalPlaylistEntry(PosCloudCacheEntry pCacheEntry) {
        URI tFileUri = URI.create(pCacheEntry.getFileUri());
        PlaylistEntry tPlaylistEntry = playlistManager.findPlaylistEntry(tFileUri);
        if (tPlaylistEntry == null) {
            tPlaylistEntry = new PlaylistEntry(new File(tFileUri));
        }
        return tPlaylistEntry;
    }

    public PosCloudCacheEntry marshalPosCloudCacheItem(PlaylistEntry pKey, HueComparableColor pValue) {
        String tFileUri = pKey.getAudioFile().toURI().toASCIIString();
        String tHexColor = Integer.toHexString(pValue.getRed())
                         + Integer.toHexString(pValue.getGreen())
                         + Integer.toHexString(pValue.getBlue());
        String tArtworkDataChecksum = "";
        ArtworkData tArtworkData = textureCacheManager.getArtworkData(pKey);
        if (tArtworkData != null) {
            tArtworkDataChecksum = tArtworkData.getChecksum().toString();
        } else if (pValue.getArtworkDataChecksum() != null) {
            tArtworkDataChecksum = pValue.getArtworkDataChecksum().toString();
        }
        return new PosCloudCacheEntry(tFileUri, "#"+tHexColor, tArtworkDataChecksum);
    }

}